package com.youlu.campus.service.system.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.system.UserDataPermission;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.system.UserDataPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;

@Service
@Slf4j
public class UserDataPermissionServiceImpl implements UserDataPermissionService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ActivityService activityService;

    @Override
    public List<UserDataPermission> list(UserDataPermission req) {
        log.info(":>>> 开始获取用户权限:{}", JSON.toJSON(req));
        if (Objects.isNull(req) || StringUtils.isBlank(req.getUserId())) {
            log.error(":>>> 获取用户数据权限错误");
            throw new BusinessException("获取用户数据权限错误");
        }
        Query query = new Query().addCriteria(Criteria.where("userId").is(req.getUserId()));
        List<UserDataPermission> datas = mongoTemplate.find(query, UserDataPermission.class);
        log.info(":>>> 用户:{} 订单分析数据:{}", req.getUserId(), datas == null ? 0 : datas.size());
        return datas;
    }

    @Override
    public boolean update(UserDataPermission req) {
        if (Objects.isNull(req) || StringUtils.isBlank(req.getUserId())) {
            log.error(":>>> 修改用户权限错误:参数错误");
            return false;
        }
        log.info(":>>> 修改用户权限:{},活动:{},数据:{}", req.getUserId(), req.getActivityInfos() == null ? 0 : req.getActivityInfos().size(), req.getDataPermission() == null ? 0 : req.getDataPermission().size());
        Query query = new Query().addCriteria(Criteria.where("userId").is(req.getUserId()));
        boolean exist = mongoTemplate.exists(query, UserDataPermission.class);
        log.info(":>>> 用户:{} 权限数据存在:{}", req.getUserId(), exist);
        if (!exist) {
            req.setId(null);
            req.setCreatedTime(new Date());
            if (!CollectionUtils.isEmpty(req.getActivityInfos())) {
                req.getActivityId().clear();
                for (ActivityInfo activityInfo : req.getActivityInfos()) {
                    req.getActivityId().add(activityInfo.getId());
                }
            }
            mongoTemplate.insert(req);
            log.info(":>>> 用户数据权限不存在:{} 新增", req.getUserId());
            return true;
        }
        Update update = new Update();
        if (!CollectionUtils.isEmpty(req.getActivityInfos())) {
            req.getActivityId().clear();
            for (ActivityInfo activityInfo : req.getActivityInfos()) {
                req.getActivityId().add(activityInfo.getId());
            }
            update.set("activityInfos", req.getActivityInfos());
            update.set("activityId", req.getActivityId());
        } else {
            update.set("activityInfos", req.getActivityInfos());
            update.set("activityId", req.getActivityId());
        }
        if (!CollectionUtils.isEmpty(req.getDataPermission())) {
            update.set("dataPermission", req.getDataPermission());
        } else {
            update.set("dataPermission", req.getDataPermission());
        }
        update.set("updatedTime", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, UserDataPermission.class);
        log.info(":>>> 修改用户权限结果:{},{}", req.getId(), updateResult.getModifiedCount() > 0 ? true : false);
        return updateResult.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public UserDataPermission findOne(String userId) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId));
        UserDataPermission u = mongoTemplate.findOne(query, UserDataPermission.class);
        log.info(":>>> 用户权限数据:{},{}", userId, u == null ? 0 : JSON.toJSON(u.getActivityId()));
        return u;
    }

    @Override
    public boolean create() {
        return false;
    }

    @Override
    public boolean addUserDataPermission(String activityId, List<String> userIds) {
        log.info(":>>> 添加用户活动数据权限:{},{}", activityId, JSON.toJSON(userIds));
        if (StringUtils.isBlank(activityId) || CollectionUtils.isEmpty(userIds)) {
            log.error(":>>> 数据参数错误");
            return false;
        }
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId).and("userId").nin(userIds));
        ActivityInfo activityInfo = activityService.findOne(activityId);
        List<UserDataPermission> userDataPermissions = mongoTemplate.find(query, UserDataPermission.class);
        if (!CollectionUtils.isEmpty(userDataPermissions)) {
            for (UserDataPermission u : userDataPermissions) {
                Query queryUpdate = new Query().addCriteria(Criteria.where("id").is(u.getId()));
                ListIterator<String> activityIdListIterator = u.getActivityId().listIterator();
                while (activityIdListIterator.hasNext()){
                    String removeActivityId = activityIdListIterator.next();
                    if(removeActivityId.equals(activityId)){
                        activityIdListIterator.remove();
                    }
                }
                ListIterator<ActivityInfo> activityInfoListIterator = u.getActivityInfos().listIterator();
                while (activityInfoListIterator.hasNext()){
                    ActivityInfo nextActivityInfo = activityInfoListIterator.next();
                    if(nextActivityInfo.getId().equals(activityId)){
                        activityInfoListIterator.remove();
                    }
                }
                Update update = new Update();
                update.set("activityId", u.getActivityId());
                update.set("activityInfos", u.getActivityInfos());
                mongoTemplate.updateFirst(queryUpdate, update, UserDataPermission.class);
            }
        }

        Date date = new Date();
        for (String userId : userIds) {
            UserDataPermission userDataPermission = this.findOne(userId);
            if (Objects.isNull(userDataPermission)) {
                userDataPermission = new UserDataPermission();
                userDataPermission.setUserId(userId);
                userDataPermission.setCreatedTime(date);
                userDataPermission.getActivityId().add(activityId);
                userDataPermission.getActivityInfos().add(activityInfo);
                mongoTemplate.insert(userDataPermission);

            } else {
                if (!userDataPermission.getActivityId().contains(activityId)) {
                    userDataPermission.getActivityId().add(activityId);
                    userDataPermission.getActivityInfos().add(activityInfo);
                    Query query1 = new Query().addCriteria(Criteria.where("id").is(userDataPermission.getId()));
                    Update update = new Update();
                    update.set("activityId", userDataPermission.getActivityId());
                    update.set("activityInfos", userDataPermission.getActivityInfos());
                    update.set("updatedTime", date);
                    mongoTemplate.updateFirst(query1, update, UserDataPermission.class);
                }

            }
        }

        return true;
    }
}
